package com.oceansoft.mobile.weixin.core;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oceansoft.mobile.weixin.util.WeixinUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.oceansoft.mobile.weixin.entity.WxToken;
import com.oceansoft.mobile.weixin.service.CoreService;
import com.oceansoft.mobile.weixin.service.WechatService;
import com.oceansoft.mobile.weixin.util.SignUtil;
  
  
/** 
 * 核心请求处理类 
 */
@Controller
@RequestMapping("coreServlet")
public class CoreServlet{
	private static Logger log=Logger.getLogger(CoreServlet.class);
	
	@Resource
	private CoreService coreService;
	
	@Resource
	private WechatService wechatService;
	
	@RequestMapping(value = "test.do", method = GET)
	public void testWeixin(HttpServletRequest request, HttpServletResponse response) {
		  coreService.processRequest(request);
	}
	
	/**
	 * 获取最新accessToken（https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx54fbed8125bea4aa&secret=f711dccbd8ef22622dac70247d3ec6dd）
	 * 获取用户信息（https://api.weixin.qq.com/cgi-bin/user/info?access_token=vIlJ5hhahlWyufQxzYuvUdaKj9GdHpIvIAdZcRVJlmWDSIwKUyRkL75qXtDapyKhfifFGD9kg0pmL0cVY6Xc-g&openid=ojZW0uHbtLl0GJmb2SlFkXOI01Ms）
	 * 修改本地址的ID值，即可作为开通开发者模式的URL(http://221.224.33.76/oswechat/coreServlet/wx.do?id=1056)
	 * @param request
	 * @param response
	 */
	@RequestMapping("wx.do")
	public void coreWeixin(HttpServletRequest request, HttpServletResponse response) {
		String method = request.getMethod();
		if(method.equalsIgnoreCase("GET")) {
			doGet(request, response);
		}
		if(method.equalsIgnoreCase("POST")) {
			doPost(request, response);
		}
	}
	
	/** 
     * 确认请求来自微信服务器 
     */  
    public void doGet(HttpServletRequest request, HttpServletResponse response){  
    	log.info("确认请求来自微信服务器log4j");
    	System.out.println("确认请求来自微信服务器");
        // 随机字符串  
        String echostr = request.getParameter("echostr");  
        
        PrintWriter out = null;
		try {
			out = response.getWriter();
			// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败  
			if (checkSignature(request)) {
				out.print(echostr);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(out!=null) {
				out.close();  
				out = null;
			}
		}
    }  
  
    /** 
     * 处理微信服务器发来的消息
     */  
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
    	log.info("处理微信服务器发来的消息");
    	System.out.println("处理微信服务器发来的消息");
    	// 响应消息
    	PrintWriter out = null;
    	try {
        	// 将请求信息的编码均设置为UTF-8（防止中文乱码）
			request.setCharacterEncoding("UTF-8");
			// 响应信息的编码均设置为UTF-8（防止中文乱码）
			response.setCharacterEncoding("UTF-8");
			if (checkSignature(request)) {
				// 调用核心业务类接收消息、处理消息
				String respMessage = coreService.processRequest(request);
				out = response.getWriter(); 
				out.print(respMessage);
			}  
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			out.close();
			out = null;
		}
    }  
    
    private boolean checkSignature(HttpServletRequest request){
    	// 微信加密签名  
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");  
        // 随机数  
        String nonce = request.getParameter("nonce");  
        
        String merid = request.getParameter("id");

        WxToken token= WeixinUtil.loadTokenByMerid(merid);

        return SignUtil.checkSignature(signature, timestamp, nonce, token.getToken());
    }
    
    
    
}   